package com.emex.app.stuff.gui;

import com.emex.app.shared.data.Position;
import com.emex.app.stuff.gui.model.PositionTableModel;
import com.emex.app.stuff.gui.model.PositionsToBuyTableModel;
import com.emex.app.stuff.provider.ShopDataProvider;
import com.emex.app.stuff.utils.ExportUtils;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import org.openide.windows.WindowManager;

/**
 *
 * @author Sergey Karavaev
 */
public class PositionsToBuyDialog extends javax.swing.JDialog {

    private List<Position> positionsToOrder = new ArrayList<>();

    /**
     * Creates new form PositionsToBuyDialog
     */
    public PositionsToBuyDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        List<Position> positions = ShopDataProvider.getInstance().getPositionsToBuy();
        positionsTable.setColumnControlVisible(true);
        positionsTable.setModel(new PositionTableModel(positions));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        copyPopUpMenu = new javax.swing.JPopupMenu();
        copyMenuItem = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        positionsTable = new org.jdesktop.swingx.JXTable();
        cancelButton = new javax.swing.JButton();
        makeOrderToBuyLink = new org.jdesktop.swingx.JXHyperlink();

        org.openide.awt.Mnemonics.setLocalizedText(copyMenuItem, org.openide.util.NbBundle.getMessage(PositionsToBuyDialog.class, "PositionsToBuyDialog.copyMenuItem.text")); // NOI18N
        copyMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyMenuItemActionPerformed(evt);
            }
        });
        copyPopUpMenu.add(copyMenuItem);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(PositionsToBuyDialog.class, "PositionsToBuyDialog.title")); // NOI18N

        positionsTable.setComponentPopupMenu(copyPopUpMenu);
        positionsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                positionsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(positionsTable);

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ok.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(PositionsToBuyDialog.class, "PositionsToBuyDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(makeOrderToBuyLink, org.openide.util.NbBundle.getMessage(PositionsToBuyDialog.class, "PositionsToBuyDialog.makeOrderToBuyLink.text")); // NOI18N
        makeOrderToBuyLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                makeOrderToBuyLinkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(makeOrderToBuyLink, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 226, Short.MAX_VALUE)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(makeOrderToBuyLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void positionsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_positionsTableMouseClicked
        if (evt.getClickCount() == 2) {
            Position selection = getPositionSelection();
            if (null != selection) {
                PositionToOrderDialog dialog = new PositionToOrderDialog(WindowManager.getDefault().getMainWindow(), true);
                dialog.setPosition(selection);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                if (null != dialog.getNewPosition() && !positionsToOrder.contains(dialog.getNewPosition())) {
                    positionsToOrder.add(dialog.getNewPosition());
                    positionsToBuyChanges();
                }
            }
        }
    }//GEN-LAST:event_positionsTableMouseClicked

    private void makeOrderToBuyLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_makeOrderToBuyLinkActionPerformed
        JPanel gui = new JPanel(new BorderLayout(3, 3));
        final JTable table = new JTable(new PositionsToBuyTableModel(positionsToOrder));
        final JScrollPane scrollPane = new JScrollPane(
                table,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        Dimension d = table.getPreferredSize();
        d.width += 250;
        table.setPreferredSize(d);
        scrollPane.setPreferredSize(
                new Dimension(d.width, table.getRowHeight() * 20));

        JButton printButton = new JButton("Печать");
        printButton.setSize(90, 23);
        printButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                JasperPrint print;
                try {
                    print = ReportGenerator.getInstance().generateDynamicReport(table, makeOrderToBuyLink.getText());
                    ReportGenerator.getInstance().showReport(print);
                } catch (JRException ex) {
                    UIUtils.showErrorMessage("Произошли ошибки при печати позиций к заказу");
                }
            }
        });

        JButton exportButton = new JButton("Экспорт в Excell");
        exportButton.setPreferredSize(new Dimension(90, 23));
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setDialogTitle("Сохранить файл как...");
                fileChooser.setSelectedFile(new java.io.File("Позиции к заказу.xls"));
                int result = fileChooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
                if (result != JFileChooser.APPROVE_OPTION) {
                    return;
                }

                try {
                    Files.write(fileChooser.getSelectedFile().toPath(), ExportUtils.exportToExcel(table));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    UIUtils.showErrorMessage("Произошли ошибки при сохранении файла");
                }
            }
        });

        gui.add(scrollPane, BorderLayout.CENTER);
        gui.add(printButton, BorderLayout.NORTH);
        gui.add(exportButton, BorderLayout.SOUTH);

        JOptionPane.showMessageDialog(null, gui, "Позиции к заказу", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_makeOrderToBuyLinkActionPerformed

    private void copyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyMenuItemActionPerformed
        Position selection = getPositionSelection();
        if (null != selection) {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Clipboard clipboard = toolkit.getSystemClipboard();
            StringSelection strSel = new StringSelection(selection.getCode());
            clipboard.setContents(strSel, null);
        }
    }//GEN-LAST:event_copyMenuItemActionPerformed

    protected Position getPositionSelection() {
        if (positionsTable.getSelectedRow() > -1) {
            Position pos = (Position) positionsTable
                    .getValueAt(positionsTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }

    protected void positionsToBuyChanges() {
        Double generalSum = 0.0;
        for (Position p : positionsToOrder) {
            generalSum += (p.getPurPrice() * p.getAmount());
        }
        makeOrderToBuyLink.setText("Позиций к заказу: " + positionsToOrder.size() + ". Общая сумма: " + generalSum + " руб.");
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JPopupMenu copyPopUpMenu;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXHyperlink makeOrderToBuyLink;
    private org.jdesktop.swingx.JXTable positionsTable;
    // End of variables declaration//GEN-END:variables
}
